<script setup lang="ts">
import type { CascaderProps } from 'ant-design-vue';

import { onMounted, ref, watch } from 'vue';

import { Cascader, Spin } from 'ant-design-vue';

import { regionQueryByParentCode } from '#/api/system/region';

defineOptions({ name: 'AddressCascader' });

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  placeholder: '请选择',
  allowClear: true,
  changeOnSelect: false,
  showCountry: false,
  isAbroad: undefined,
});

const emit = defineEmits(['blur', 'change']);

interface Props {
  disabled?: boolean;
  placeholder?: string;
  allowClear?: boolean;
  changeOnSelect?: boolean;
  showCountry?: boolean;
  isAbroad?: number | undefined;
}

const loading = ref(false);
const countryLoading = ref(false);
const initializing = ref(false); // 初始化中
const options = ref<CascaderProps['options']>([]);

const modelValue = defineModel<(number | string)[]>('value', {
  default: () => [],
});

watch(
  () => modelValue.value,
  (val, oldVal) => {
    if (!val || val.length === 0) return;
    console.log('地址级联组件watch:', val, oldVal);
    init();
  },
  { immediate: true },
);

watch(
  () => props.isAbroad,
  async () => {
    options.value = (options.value || []).map((item) => {
      item.disabled =
        (props.isAbroad === 1 && item.value === '00') ||
        (props.isAbroad === 0 && item.value !== '00');
      return item;
    });
  },
);

// watchEffect(() => {
//   if (modelValue.value.length > 0) {
//     console.log('watchEffect变化', modelValue.value);
//     // if (!inited.value) {
//     init();
//     // }
//   }
// });

async function loadData(selectedOptions: any) {
  console.log('地址级联组件触发loadData', selectedOptions);
  const targetOption = selectedOptions[selectedOptions.length - 1];
  targetOption.loading = true;

  // 加载子集数据
  await loadChildren(targetOption.value, targetOption);
  targetOption.loading = false;
}

// 查询国家作为一级
async function loadCountrys() {
  try {
    if (countryLoading.value) return;
    countryLoading.value = true;
    if (options.value && options.value.length > 0) {
      countryLoading.value = false;
      return;
    }
    const list = await regionQueryByParentCode('0');
    options.value = list.map((item) => {
      // 标记是否为叶子节点，设置了 `loadData` 时有效
      // 设为 `false` 时会强制标记为父节点，即使当前节点没有 children，也会显示展开图标
      return {
        label: item.name,
        value: item.code,
        isLeaf: item.code !== '00',
        children: [],
        disabled:
          (props.isAbroad === 1 && item.code === '00') ||
          (props.isAbroad === 0 && item.code !== '00'),
      };
    });
    console.log('获取国家列表', options.value.length);
  } finally {
    countryLoading.value = false;
  }
}

// // 查询省份作为一级
// async function loadProvinces() {
//   const list = await regionQueryByParentCode('00');
//   options.value = list.map((item) => {
//     return { label: item.name, value: item.code, isLeaf: false };
//   });
// }

// 查询子集数据
async function loadChildren(code: number | string, targetOpt?: any) {
  try {
    const list = code ? await regionQueryByParentCode(code) : [];
    const targetOption =
      targetOpt || options.value?.find((item) => item.value === code);
    if (targetOption) {
      if (list.length > 0) {
        targetOption.children = list.map((item) => {
          return {
            label: item.name,
            value: item.code,
            isLeaf: item.level >= 3,
            children: [],
          };
        });
      } else {
        targetOption.children = [];
        targetOption.isLeaf = true;
      }
    }
  } catch (error) {
    console.log(error);
  }
}

onMounted(async () => {
  console.log('地址级联组件onMounted:', modelValue.value);
  // 处理编辑场景含初始值
  await init();
});

async function init() {
  console.log('地址级联组件执行init');
  if (initializing.value) return;
  initializing.value = true;
  await loadCountrys();

  if (modelValue.value?.length > 0) {
    loading.value = true;

    const countryCode = modelValue.value[0];
    if (countryCode !== '00') {
      // 海外，非中国
      loading.value = false;
      return;
    }

    const targetCountryOption = options.value?.find(
      (item) => item.value === countryCode,
    );
    if (targetCountryOption?.children?.length === 0) {
      await loadChildren(countryCode);
    }

    const provinceCode = modelValue.value[1];
    if (provinceCode) {
      console.log(provinceCode, targetCountryOption);
      const targetProvinceOption = targetCountryOption?.children?.find(
        (item) => item.value === provinceCode,
      );
      if (targetProvinceOption?.children?.length === 0) {
        await loadChildren(provinceCode, targetProvinceOption);
      }

      const cityCode = modelValue.value[2];
      if (cityCode) {
        const targetCityOption = targetProvinceOption?.children?.find(
          (item) => item.value === cityCode,
        );
        if (targetCityOption?.children?.length === 0) {
          await loadChildren(cityCode, targetCityOption);
        }
      }
    }

    loading.value = false;
  }

  initializing.value = false;
}

function handleChange() {
  console.log('地址级联组件触发change:', modelValue.value);
  emit('change', modelValue.value);
}
</script>

<template>
  <div class="flex w-full gap-1">
    <Spin :spinning="loading" class="w-full">
      <Cascader
        v-model:value="modelValue"
        :options="options"
        :load-data="loadData"
        class="w-full"
        :placeholder="placeholder"
        :change-on-select="changeOnSelect"
        :allow-clear="allowClear"
        @blur="emit('blur')"
        @change="handleChange"
      />
    </Spin>
  </div>
</template>

<style lang="scss" scoped>
:deep(.ant-spin-nested-loading) {
  width: 100%;
}
</style>
